package demo11.gumballl;

public class GumballMachine {//口香糖贩卖机
//状态
	final static int SOLD_OUT = 0;//卖完了
	final static int NO_QUARTER = 1;//没有投入25分钱
	final static int HAS_QUARTER = 2;//投入25分钱
	final static int SOLD = 3;//出售
 //实例变量
	int state = SOLD_OUT;//默认状态
	int count = 0;//数量
  //构造方法
	public GumballMachine(int count) {
		this.count = count;
		if (count > 0) {
			state = NO_QUARTER;
		}
	}
	/*如何对对象内的状态建模---
	 *           ：通过创建一个实例变量来持有状态值并在方法内写条件代码处理不同的状态*/
	//顾客投入25分
	public void insertQuarter() {
		if (state == HAS_QUARTER) {
			System.out.println("不能插入另一个25分。");
		} else if (state == NO_QUARTER) {
			state = HAS_QUARTER;
			System.out.println("你插了一个25分");
		} else if (state == SOLD_OUT) {
			System.out.println("你不能插入25分，机器已经卖完了。");
		} else if (state == SOLD) {
        	System.out.println("请稍等，我们已经给你一个口香糖");
		}
	}
//顾客退出25分
	public void ejectQuarter() {
		if (state == HAS_QUARTER) {
			System.out.println("25分已经回退。");
			state = NO_QUARTER;
		} else if (state == NO_QUARTER) {
			System.out.println("你还没有投入25分");
		} else if (state == SOLD) {
			System.out.println("对不起，你已经转动曲柄了拿到口香糖。");
		} else if (state == SOLD_OUT) {
        	System.out.println("你不能退钱，你还没有投入。");
		}
	}
 //转动曲柄
	public void turnCrank() {
		if (state == SOLD) {
			System.out.println("一次投币即使转了两圈不会让你得到另一个口香糖!");
		} else if (state == NO_QUARTER) {
			System.out.println("需要先投入25分钱");
		} else if (state == SOLD_OUT) {
			System.out.println("不能给你糖果，已经没有口香糖");
		} else if (state == HAS_QUARTER) {
			System.out.println("成功拿到糖果...");
			state = SOLD;//出售
			dispense();
		}
	}
 //发放糖果
	private void dispense() {
		if (state == SOLD) {
			System.out.println("一个口香糖来轧出槽");
			count = count - 1;
			if (count == 0) {
				System.out.println("糖果已经售罄!");
				state = SOLD_OUT;
			} else {
				state = NO_QUARTER;
			}
		} else if (state == NO_QUARTER) {
			System.out.println("你需要先付钱。");
		} else if (state == SOLD_OUT) {
			System.out.println("没有投入25分，没有糖果分发");
		} else if (state == HAS_QUARTER) {
			System.out.println("（你就已经退钱or...）没有糖果分发");
		}
	}
 //再次填充糖果
	public void refill(int numGumBalls) {
		this.count = numGumBalls;
		state = NO_QUARTER;
		System.out.println("机器已经有糖了");
	}

	@Override
	public String toString() {
		StringBuffer result = new StringBuffer();
		result.append("\njava站口香糖模型机器\n");
		result.append("库存: " + count + " 口香糖");
		if (count != 1) {
			result.append("SSS");
		}
		result.append("\n机器状态 ");
		if (state == SOLD_OUT) {
			result.append("卖完了");
		} else if (state == NO_QUARTER) {
			result.append("等待投入25分");
		} else if (state == HAS_QUARTER) {
			result.append("已经投入25分");
		} else if (state == SOLD) {
			result.append("提供一个口香糖");
		}
		result.append("\n");
		return result.toString();
	}
}
